<template>
  <!-- 人员信息表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1100"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="7">
          <el-form-item label="员工号" prop="empNo">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.empNo"
              placeholder="请输入员工号"
              clearable
            />
            <span v-else>{{ formData.empNo }}</span>
          </el-form-item></el-col
        >
        <el-col :span="7">
          <el-form-item label="姓名" prop="personName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.personName"
              placeholder="请输入姓名"
              clearable
            />

            <span v-else>{{ formData.personName }}</span>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item label="性别" prop="sex">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.sex"
              placeholder="请选择性别"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('SexType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{ useDictionary("SexType", formData.sex) }}</span>
          </el-form-item></el-col
        >
        <el-col :span="7">
          <el-form-item label="学历" prop="education">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.education"
              placeholder="请选择学历"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('EducationType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("EducationType", formData.education)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item label="入职日期" prop="entryDate">
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.entryDate"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              placeholder="请选择入职日期"
            />

            <span v-else>{{ formData.entryDate }}</span>
          </el-form-item></el-col
        >
        <el-col :span="7">
          <el-form-item label="出生日期" prop="birthday">
            <!-- <el-input
              v-if="!props.isReadonly"
              v-model="formData.birthday"
              placeholder="请输入出生日期"
              clearable
            /> -->
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.birthday"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              placeholder="请选择出生日期"
            />
            <span v-else>{{ formData.birthday }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <!-- <el-form-item label="所在部门" prop="departmentId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.departmentId"
              placeholder="请选择所在部门"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select> -->
          <el-form-item label="所在部门" prop="departmentId">
            <template #default="scope">
              <el-tree-select
                v-if="!props.isReadonly"
                placeholder="请选择所在部门"
                style="width: 300px"
                filterable
                v-model="formData.departmentId"
                :data="plantList"
                node-key="id"
                clearable
                :props="{ label: 'organizationName', children: 'nodes' }"
                check-strictly
                :render-after-expand="false"
              />
              <span v-else>{{ formData.departmentName }}</span>
            </template>

            <!-- </el-form-item>
            <span v-else>{{ plantReadOnly }}</span> -->
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="岗位" prop="post">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.post"
              placeholder="请选择岗位"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('PostType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{ useDictionary("PostType", formData.post) }}</span>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="7">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.contactPhone"
              placeholder="请输入联系电话"
              clearable
            />

            <span v-else>{{ formData.contactPhone }}</span>
          </el-form-item></el-col
        >
        <el-col :span="7">
          <el-form-item label="电子邮件" prop="email">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.email"
              placeholder="请输入电子邮件"
              clearable
            />

            <span v-else>{{ formData.email }}</span>
          </el-form-item></el-col
        >
        <el-col :span="7">
          <el-form-item label="人员状态" prop="personStatus">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.personStatus"
              placeholder="请选择人员状态"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('personStatus')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("personStatus", formData.personStatus)
            }}</span>
          </el-form-item></el-col
        >
      </el-row>

      <el-form-item label="唯一识别码" prop="identificationCode">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.identificationCode"
          placeholder="请输入唯一识别码"
          clearable
          style="width: 810px"
        />

        <span v-else>{{ formData.identificationCode }}</span>
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.remarks"
          placeholder="请输入备注"
          clearable
          style="width: 810px"
        />
        <span v-else>{{ formData.remarks }}</span>
      </el-form-item>

      <!-- 照片 -->
      <el-form-item
        prop="imgUrl"
        style="position: absolute; top: 90px; right: 230px"
      >
        <upload-imge
          :action="`${actionUrl}/system/fileCenter/uploadFile/file`"
          v-model="formData.imgUrl"
          :domainName="`${actionUrl}`"
          :isReadonly="props.isReadonly"
        ></upload-imge>
        <el-input v-model="formData.imgUrl" style="display: none"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useDictionary } from "@/utils/useTable";
import dayjs from "dayjs";

defineOptions({
  name: "MDMMDMPERSONINFOADDORUPDATE",
  inheritAttrs: false,
});
// 图片地址
const actionUrl = import.meta.env.VITE_APP_BASE_API;
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  departmentId: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  empNo: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入员工号",
      trigger: "blur",
    },
    {
      required: true,
      message: "请输入员工号",
      trigger: "blur",
    },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  personName: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入姓名",
      trigger: "blur",
    },
    {
      required: true,
      message: "请输入姓名",
      trigger: "blur",
    },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  // imgUrl: [{ required: true, message: "请输上传图片", trigger: "change" }],
  sex: [{ required: true, message: "请输入性别", trigger: "change" }],
  // birthday: [
  //   {
  //     required: true,
  //     message: "请输入出生日期",
  //     trigger: "blur",
  //   },
  // ],
  // education: [{ required: true, message: "请输入学历", trigger: "change" }],
  entryDate: [
    {
      required: true,
      message: "请输入入职日期",
      trigger: "blur",
    },
  ],
  departmentId: [{ required: true, message: "请输入部门", trigger: "change" }],
  // post: [{ required: true, message: "请输入岗位", trigger: "change" }],
  contactPhone: [
    // {
    //   required: true,
    //   pattern: "[^ \x20]+",
    //   message: "请输入联系电话",
    //   trigger: "blur",
    // },
    // {
    //   required: true,
    //   message: "请输入联系电话",
    //   trigger: "blur",
    // },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  email: [
    // {
    //   required: true,
    //   pattern: "[^ \x20]+",
    //   message: "请输入电子邮件",
    //   trigger: "blur",
    // },
    // {
    //   required: true,
    //   message: "请输入电子邮件",
    //   trigger: "blur",
    // },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  personStatus: [
    { required: true, message: "请输入人员状态", trigger: "change" },
  ],
  identificationCode: [
    // {
    //   required: true,
    //   pattern: "[^ \x20]+",
    //   message: "请输入唯一识别码",
    //   trigger: "blur",
    // },
    // {
    //   required: true,
    //   message: "请输入唯一识别码",
    //   trigger: "blur",
    // },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  empNo: "",
  personName: "",
  imgUrl: "",
  sex: "",
  birthday: "",
  education: "",
  entryDate: "",
  organizationId: "",
  organizationCode: "",
  departmentId: "",
  post: "",
  contactPhone: "",
  email: "",
  personStatus: "1",
  identificationCode: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  departmentName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        empNo,
        personName,
        imgUrl,
        sex,
        birthday,
        education,
        entryDate,
        organizationId,
        organizationCode,
        departmentId,
        post,
        contactPhone,
        email,
        personStatus,
        identificationCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        departmentName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        empNo,
        personName,
        imgUrl,
        sex,
        birthday,
        education,
        entryDate,
        organizationId,
        organizationCode,
        departmentId,
        post,
        contactPhone,
        email,
        personStatus,
        identificationCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        departmentName,
      });
      formData.birthday = formData.birthday
        ? dayjs(formData.birthday).format("YYYY-MM-DD")
        : "";
      formData.entryDate = dayjs(formData.entryDate).format("YYYY-MM-DD");
    }
  }
);

watch(
  () => props.departmentId,
  (newVal: string) => {
    if (newVal != "" && formData.id == "") {
      formData.departmentId = props.departmentId;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();

  formData.id = "";
  formData.version = "";
  formData.empNo = "";
  formData.personName = "";
  formData.imgUrl = "";
  formData.sex = "";
  formData.birthday = "";
  formData.education = "";
  formData.entryDate = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.departmentId = "";
  formData.post = "";
  formData.contactPhone = "";
  formData.email = "";
  formData.personStatus = "1";
  formData.identificationCode = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.departmentName = "";
}

const loading = ref(false);

/** 人员信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmpersoninfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();

      emit("reset-table", formData.id);
    }
  });
}

// 获取部门列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getTree",
    method: "post",
    data: {},
  });

  plantList.value = res1.data;
  console.log(plantList.value);
};
// id转化成部门名称
// const plantReadOnly = ref("");
// const plantReadOnlyFn = () => {
//   plantList.value.forEach((item: any) => {
//     if (item.plantId == formData.departmentId) {
//       plantReadOnly.value = item.organizationName;
//     }
//   });
// };

onMounted(() => {
  getPlantList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style scoped lang="scss">
.avatar-uploader {
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;

    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .el-upload:hover {
    border-color: var(--el-color-primary);
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;

  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
}
</style>
